package net.loyin.jfinal.dialect;

import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import net.loyin.utils.IdGenerater;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by loyin on 16/1/12.
 */
public class MyPostgreSqlDialect extends PostgreSqlDialect {
    @Override
    public void forModelSave(Table table, Map<String, Object> attrs, StringBuilder sql, List<Object> paras) {
        sql.append("insert into \"").append(table.getName()).append("\"(");
        StringBuilder temp = new StringBuilder(") values(");
        Iterator i$ = attrs.entrySet().iterator();
        String primaryKey=table.getPrimaryKey()[0].toLowerCase();

        while(i$.hasNext()) {
            Map.Entry e = (Map.Entry)i$.next();
            String colName = (String)e.getKey();
            if(table.hasColumnLabel(colName)) {
                if(paras.size() > 0) {
                    sql.append(", ");
                    temp.append(", ");
                }
                sql.append("\"").append(colName).append("\"");
                temp.append("?");
                if(colName.equals(primaryKey)){
                    paras.add(IdGenerater.me.idValTo62());
                }else if("create_datetime".equals(colName)){
                    paras.add(new Timestamp(new Date().getTime()));
                }else{
                    paras.add(e.getValue());
                }
            }
        }

        sql.append(temp.toString()).append(")");
    }
}
